﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PB.Base;
using PB.Enums;

namespace PB.Helpers.CustomCollections
{
    public sealed class UsersCollection : ICollection<User>
    {        
        public UsersCollection(bool userOwnerLogs)
        {
            this._userOwnerLogs = userOwnerLogs;
        }

        private bool _userOwnerLogs = false;

        internal List<User> users = XmlHelper.Users.GetUsers();

        public User this[int index]
        {
            get
            {
                return this.users[index];
            }
            set
            {
                this.users[index] = value;

                this.Add(value);
            }
        }

        public void Add(User item)
        {            
            if (!XmlHelper.Users.ContainsUser(item))
            {
                DateTime oldDt = item.CreatedDateTime;

                if (item.CreatedDateTime.IsNull() || item.CreatedDateTime != DateTime.Now) item.CreatedDateTime = DateTime.Now;

                this.users.Add(item);

                XmlHelper.Users.WriteUser(item);

                item.CreatedDateTime = oldDt;
            }
            else
            {
                throw new ArgumentException("The user that you trying to add is already exists.");
            }
        }

        public void Clear()
        {
            this.users.Clear();

            XmlHelper.Users.DeleteAllUsers();
        }

        public bool Contains(User item)
        {
            return XmlHelper.Users.ContainsUser(item);
        }

        public void CopyTo(User[] array, int arrayIndex)
        {
            this.users.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return this.users.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(User item)
        {
            bool rtn = false;

            var logs = XmlHelper.Logs.GetLogs();

            var logType = logs.Where(u => u.User != null && u.User.Username == item.Username).Single().LogType;

            Log log = new Log()
            {
                User = item,
                LogType = logType
            };

            XmlHelper.Logs.DeleteLog(log, this._userOwnerLogs);

            XmlHelper.Users.DeleteUser(item);

            rtn = this.users.Remove(item);

            return rtn;
        }

        public IEnumerator<User> GetEnumerator()
        {
            return this.users.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}
